package com.yc.springmvc.web;

import lombok.SneakyThrows;
import org.springframework.core.convert.converter.Converter;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimestampConvertor implements Converter<String, Timestamp> {

    SimpleDateFormat YYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat YYYYMMDDHHMMSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Timestamp convert(String source) {
        // yyyy-MM-dd   yyyy-MM-dd HH:mm:ss
        if(source == null){
            return null;
        } else if(source.matches("\\d{4}-\\d{2}-\\d{2}")){
            Date date = null;
            try {
                date = YYYYMMDD.parse(source);
            } catch (ParseException e) {
                throw new RuntimeException("日期格式错误!",e);
            }
            return new Timestamp(date.getTime());
        } else if(source.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")){
            Date date = null;
            try {
                date = YYYYMMDDHHMMSS.parse(source);
            } catch (ParseException e) {
                throw new RuntimeException("日期格式错误!",e);
            }
            return new Timestamp(date.getTime());
        } else {
            throw new RuntimeException("日期格式不支持!");
        }
    }
}
